<?php
namespace app\admin\controller;

use think\Exception;
use think\Request;
use app\common\model\Address as AddressModel;
use think\Db;

/**
 * 跟平台有关的api的调用
 * Class Busapi
 * @package app\admin\controller
 */
class Busapi extends Base {

    protected $api_hosts = 'http://318.ogmall.com';

    protected $request_param = [
        'token'=>'',
    ];

    public function __construct(Request $request)
    {
        parent::__construct($request);
        $key = 'ogmall-small-program';
        $this->request_param['token'] = $this->getEncrypt($key);
    }



    public function updateProvince(){
        $this->success("更新成功");
        $api = $this->api_hosts.'/api/getProvinces';
        $query = http_build_query($this->request_param);
        $api .= "?".$query;
        $provinces = $this->curl($api);

        $provinces = json_decode($provinces,true);
        if( !$provinces || !$provinces['status'] ){
            throw new \Exception("省份数据错误");
        }
        $now = time();
        $res = Db::query('truncate table address');
        foreach( $provinces['data'] as $key => &$val ){
            $val['apid'] = 0;
            $val['type'] = 0;
            $val['update_time'] = $now;
            $val['aid'] = $val['id'];// aid 是平台id
            unset($val['id']);
        }
        unset($val);
        $res = Db::table('address')->insertAll($provinces['data']);

        $this->success("更新省份成功",'',$provinces['data']);

    }

    /**
     * @param Request $request
     */
    public function updateCity(Request $request){
        $province_id = $request->param('province_id');

        $api    = $this->api_hosts.'/api/getCities';
        $this->request_param['provinceId'] = $this->getEncrypt($province_id);
        $query  = http_build_query($this->request_param);
        $api   .= "?".$query;
        $cities = $this->curl($api);
        $cities = json_decode($cities,true);
        $now = time();
        if($cities['status']){
            foreach( $cities['data'] as $key => &$val ){
                $val['apid'] = $province_id;
                $val['type'] = 1;
                $val['update_time'] = $now;
                $val['aid'] = $val['id'];
                unset($val['id']);
            }
            unset($val);
            $res = Db::table('address')->insertAll($cities['data']);
            $this->success("更新成功",'',$cities['data']);
        }
        $this->success("更新成功",'',[]);
    }


    /**
     * 系统禁止了 多进程函数 可以利用curl来模拟 这样不就ok了
     * @param Request $request
     */
    public function updateDistrict(Request $request){
        $city_id = $request->param('city_id');
        $api = $this->api_hosts.'/api/getDistricts';
        $this->request_param['cityId'] = $this->getEncrypt($city_id);
        $query = http_build_query($this->request_param);
        $api .= "?".$query;
        $districts = $this->curl($api);
        $districts = json_decode($districts,true);
        $now = time();
        if($districts['status']){
            foreach( $districts['data'] as $key => &$val ){
                $val['apid'] = $city_id;
                $val['type'] = 2;
                $val['update_time'] = $now;
                $val['aid'] = $val['id'];
                unset($val['id']);
            }
            unset($val);
            $res = Db::table('address')->insertAll($districts['data']);
            $this->success("更新成功",'',$districts['data']);
        }
        $this->success("更新成功",'',[]);
    }




    /**
     * 获取所有地区
     */
    public function getAllDistrict(){
        $data = AddressModel::where('type',2)->select();
        $data = collection($data)->toArray();
        $this->success("获取成功",'',$data);
    }


    /**
     * 更新B端和城市运营商的数据  还要增加一个判断是否单进程 不能并发操作
     * @throws
     */
    public function updateCompany(){
        $address = AddressModel::where(['type'=>2,'get_company'=>'0'])->order('id desc')->find();
        //$address = AddressModel::where(['type'=>2,'aid'=>'1801','get_company'=>0])->order('id desc')->find();
        if(!$address){
            $this->error("更新完毕");
        }

        $api = $this->api_hosts.'/api/getCompanys';
        $district_id = $address->aid; //老平台的地址id
        $this->request_param['districtId'] = $this->getEncrypt($district_id);
        $query = http_build_query($this->request_param);
        $api .= "?".$query;
        $companies = $this->curl($api);
        $companies = json_decode($companies,true);

        if($companies['status']){
            //有公司数据  先构造地址
            $district_id = $address['aid'];
            $city_id = 0;
            $province_id = 0;
            $belong_to = 0;

            $city = AddressModel::where(['type'=>1])->where('aid',$address['apid'])->find();
            if($city){
                $city_id = $city['aid'];
                $province = AddressModel::where(['type'=>0])->where('aid',$city['apid'])->find();
                if($province){
                    $province_id = $province['aid'];
                }
            }
            $companies = $companies['data'];
            $data = [];
            $now = time();
            if(!empty($companies['agentData'])){
                //$belong_to = $companies['agentData']["agentUId"]; //给装修公司赋值用 但是公司的id 在本地要用本地数据
                $data['company_name'] = $companies['agentData']['agentName'];
                $data['company_id']   = $companies['agentData']["agentUId"];
                $data['update_time']  = $now;
                $data['province_id']  = $province_id;
                $data['city_id']      = $city_id;
                $data['district_id']  = $district_id;//对与城市运营商 这个值有没有都无所谓了 因为一个城市管几个区 这里以后看看怎么弄
                $data['type']         = 1;
                $company = Db::table('company')->where('company_id',$data['company_id'])->where('type','1')->find(); //加上type 过滤是为了防止 平台方 id跟地址id一样重复 就糟糕   address的id 市和区会有重复的id 好烦
                if($company){
                    Db::table('company')->where('company_id',$data['company_id'])->where('type','1')->update($data);
                    $belong_to = $company['id'];  //belong_to 用本地id
                }else{
                    $id = Db::table('company')->insertGetId($data);
                    $belong_to = $id;
                }
            }
            $data = [];
            if(!empty($companies['companyData'])){
                foreach($companies['companyData'] as $key => $val){
                    $data['company_name'] = $val['companyName'];
                    $data['company_id']   = $val['companyUId'];
                    $data['update_time']  = $now;
                    $data['province_id']  = $province_id;
                    $data['city_id']      = $city_id;
                    $data['district_id']  = $val['districtId'];
                    $data['belong_to']    = $belong_to;
                    $data['type']         = 0;
                    $company = Db::table('company')->where('company_id',$data['company_id'])->where('type','0')->count(); //加上type 过滤是为了防止 平台方 id跟地址id一样重复 就糟糕
                    if($company){
                        Db::table('company')->where('company_id',$data['company_id'])->where('type','0')->update($data);
                    }else{
                        Db::table('company')->insert($data);
                    }
                }
            }


        }
        AddressModel::update(['get_company'=>'1'],['id'=>$address['id']]);
        $this->success($address['name']." 更新成功...");
        //如果有数据 这里应该是先保存 再打散然后随机的排列数据 保证公平

    }







    /**
     * post 请求
     * @param $url
     * @return mixed
     */
    protected function curl($url){
        $ch  = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
    }

    /**
     * 接口加密
     * @param string $data
     * @return string
     */
    public function getEncrypt($data){
        $result = exec('java AES '.$data,$encrypt,$return_var);
        return $result;
    }



}
